<?php

namespace App\Imports;

use App\Models\Setting\SysSetting;
use App\Models\User\ChengBao;
use App\Models\User\ChengBaoSum;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithCalculatedFormulas;

class ChengBaoImport implements ToCollection,WithCalculatedFormulas
{

    public $count;
    public $baoSumPrice;
    public $servicePrice;
    public $account;
    public $msg;
    public $success = true;

    public function __construct($account) {
        $this->account = $account;
    }

    /**
    * @param Collection $collection
    */
    public function collection(Collection $collection) {

        $d = 25569;
        $t = 24 * 60 * 60;

        $orders = $collection->toArray();
        unset($orders[0]);
        $info = [];
        $time = date('Y-m-d H:i:s');
        //dd($orders);
        $import_number = uniqid();
        foreach ($orders as $k=>$order) {

            if(count(array_filter($order))>0){
                $row = $k+1;
                if(empty($order[5])){
                    $this->success = false;
                    $this->msg = "导入失败！$row 行左右，保单号不能为空！";
                    return;
                }
                if(empty($order[6])){
                    $this->success = false;
                    $this->msg = "导入失败！$row 行左右，车牌号不能为空！";
                    return;
                }
                if(empty($order[8])){
                    $this->success = false;
                    $this->msg = "导入失败！$row 行左右，被保险人不能为空！";
                    return;
                }
                if(empty($order[20])){
                    $this->success = false;
                    $this->msg = "导入失败！$row 行左右，车架号不能为空！";
                    return;
                }



                $info[] = [
                    'import_number'=>$import_number,
                    'service_buy_date'=>is_numeric($order[0])?gmdate('Y-m-d', ($order[0] - $d) * $t):$order[0],
                    'san_ji_organ'=>$order[1],
                    'organ_name'=>$order[2],
                    'jue_ce_unit'=>$order[3],
                    'baoxian_type'=>$order[4],
                    'baodan_order_number'=>$order[5],
                    'car_number'=>$order[6],
                    'toubao_name'=>$order[7],
                    'beibao_name'=>$order[8],
                    'toubao_date'=>is_numeric($order[9])?gmdate('Y-m-d', ($order[9] - $d) * $t):$order[9],
                    'baoxian_s_date'=>is_numeric($order[10])?gmdate('Y-m-d', ($order[10] - $d) * $t):$order[10],
                    'baoxian_e_date'=>is_numeric($order[11])?gmdate('Y-m-d', ($order[11] - $d) * $t):$order[11],
                    'he_bao_date'=>is_numeric($order[12])?gmdate('Y-m-d', ($order[12] - $d) * $t):$order[12],
                    'san_zhe_xian_bao_price'=>$order[13],
                    'cheng_jia_yi_wai_price'=>$order[14],
                    'shang_ye_che_shang_price'=>$order[15],
                    'car_ship_price'=>$order[16],
                    'baoxian_shui_price'=>$order[17],
                    'baoxian_not_shui_price'=>$order[18],
                    'car_type_name'=>$order[19],
                    'car_jia_number'=>$order[20],
                    'enginee_number'=>$order[21],
                    'car_type'=>$order[22],
                    'chu_deng_date'=>is_numeric($order[23])?gmdate('Y-m-d', ($order[23] - $d) * $t):$order[23],
                    'use_way'=>$order[24],
                    'seat'=>$order[25],
                    'account'=>$this->account,
                    'created_at'=>$time,
                    'updated_at'=>$time,
                ];
            }

        }

        $this->count = count($info);
        $this->baoSumPrice = round(array_sum(array_column($info, 'baoxian_not_shui_price')),2);

        $rate = SysSetting::where('key','service_rate')->first()->val??0.02;
        $this->servicePrice = round($this->baoSumPrice * $rate,2);
        if($this->count<=0){
            return;
        }
        //dd($this->count,$this->servicePrice);
        //检查如数重复
        $repeat = ChengBao::whereIn('baodan_order_number',array_column($info, 'baodan_order_number'))->get(['baodan_order_number']);
        if($repeat->count()>0){
            $this->success = false;
            $this->msg = '导入失败！数据有重复，请删除后再导入！';
            return;
        }

        try{
            DB::beginTransaction();
            ChengBaoSum::updateOrCreate(['import_number'=>$import_number],[
                'account'=>$this->account,
                'records_count'=>count($info),
                'bao_sum_price'=>$this->baoSumPrice,
                'service_price'=>$this->servicePrice,
                'import_number'=>$import_number,
            ]);
            ChengBao::insert($info);
            DB::commit();
            $this->msg = "本次共导入：$this->count 条记录，保费：$this->baoSumPrice ，服务费：$this->servicePrice";
            Log::info($this->msg);
        }catch(\Exception $e){
            DB::rollback();
            $this->success = false;
            $this->msg = $tip = '导入失败！'. $e->getFile().':'.$e->getLine().':'.$e->getMessage();
            Log::error($tip);
        }



    }
}
